<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>ReentrantLock 详解 | flybird&#39;s blog</title>
    <meta name="generator" content="VuePress 1.8.0">
    <link rel="icon" href="https://infinitypro-img.infinitynewtab.com/custom-icon/8001de1jd3n68lbfnxxt564xvb0vl5.png?imageMogr2/thumbnail/240x/format/webp/blur/1x0/quality/100|imageslim">
    <script language="javascript" type="text/javascript" src="https://cdn.staticfile.org/jquery/1.7.2/jquery.min.js"></script>
    <script language="javascript" type="text/javascript" src="/js/MouseClickEffect.js"></script>
    <meta name="description" content="Stay hungry, Stay foolish">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    
    <link rel="preload" href="/assets/css/0.styles.324c77a5.css" as="style"><link rel="preload" href="/assets/js/app.55c4f7c3.js" as="script"><link rel="preload" href="/assets/js/5.86109dd2.js" as="script"><link rel="preload" href="/assets/js/1.74974061.js" as="script"><link rel="preload" href="/assets/js/2.ab8aa845.js" as="script"><link rel="preload" href="/assets/js/66.cb493053.js" as="script"><link rel="preload" href="/assets/js/18.cfe435f1.js" as="script"><link rel="prefetch" href="/assets/js/10.1f3187f9.js"><link rel="prefetch" href="/assets/js/11.67fe3d1f.js"><link rel="prefetch" href="/assets/js/12.0052f325.js"><link rel="prefetch" href="/assets/js/13.bad60b36.js"><link rel="prefetch" href="/assets/js/14.6a893378.js"><link rel="prefetch" href="/assets/js/15.899648d3.js"><link rel="prefetch" href="/assets/js/16.0575f88b.js"><link rel="prefetch" href="/assets/js/17.86f820d7.js"><link rel="prefetch" href="/assets/js/19.1d1c7b67.js"><link rel="prefetch" href="/assets/js/20.218819f6.js"><link rel="prefetch" href="/assets/js/21.223949af.js"><link rel="prefetch" href="/assets/js/22.eb6ea80c.js"><link rel="prefetch" href="/assets/js/23.cf07ba0c.js"><link rel="prefetch" href="/assets/js/24.eeb9d511.js"><link rel="prefetch" href="/assets/js/25.4be64ae7.js"><link rel="prefetch" href="/assets/js/26.6aea0ced.js"><link rel="prefetch" href="/assets/js/27.7540f161.js"><link rel="prefetch" href="/assets/js/28.d88a26e6.js"><link rel="prefetch" href="/assets/js/29.7edc404c.js"><link rel="prefetch" href="/assets/js/30.b3c16bef.js"><link rel="prefetch" href="/assets/js/31.63392d40.js"><link rel="prefetch" href="/assets/js/32.b90695c8.js"><link rel="prefetch" href="/assets/js/33.669186a5.js"><link rel="prefetch" href="/assets/js/34.57a9b7fc.js"><link rel="prefetch" href="/assets/js/35.81d5b8b3.js"><link rel="prefetch" href="/assets/js/36.466fde53.js"><link rel="prefetch" href="/assets/js/37.ff7b9321.js"><link rel="prefetch" href="/assets/js/38.132de18a.js"><link rel="prefetch" href="/assets/js/39.80a51963.js"><link rel="prefetch" href="/assets/js/40.e7d6c67d.js"><link rel="prefetch" href="/assets/js/41.d195ea4b.js"><link rel="prefetch" href="/assets/js/42.dbe1a8f1.js"><link rel="prefetch" href="/assets/js/43.2ea02aec.js"><link rel="prefetch" href="/assets/js/44.294015bc.js"><link rel="prefetch" href="/assets/js/45.3cf9c326.js"><link rel="prefetch" href="/assets/js/46.8cc95701.js"><link rel="prefetch" href="/assets/js/47.ddf6cc44.js"><link rel="prefetch" href="/assets/js/48.ba718ca6.js"><link rel="prefetch" href="/assets/js/49.feee5279.js"><link rel="prefetch" href="/assets/js/50.6f2d0d0d.js"><link rel="prefetch" href="/assets/js/51.ebe1eb07.js"><link rel="prefetch" href="/assets/js/52.3e47f7ae.js"><link rel="prefetch" href="/assets/js/53.861fb703.js"><link rel="prefetch" href="/assets/js/54.f7d3a937.js"><link rel="prefetch" href="/assets/js/55.d90baa98.js"><link rel="prefetch" href="/assets/js/56.ba7f3256.js"><link rel="prefetch" href="/assets/js/57.90441d7f.js"><link rel="prefetch" href="/assets/js/58.a0d58abc.js"><link rel="prefetch" href="/assets/js/59.7f649313.js"><link rel="prefetch" href="/assets/js/6.00dfc51e.js"><link rel="prefetch" href="/assets/js/60.60dd83d2.js"><link rel="prefetch" href="/assets/js/61.b84cd1ef.js"><link rel="prefetch" href="/assets/js/62.8ed6541f.js"><link rel="prefetch" href="/assets/js/63.84bfbbbf.js"><link rel="prefetch" href="/assets/js/64.01c483db.js"><link rel="prefetch" href="/assets/js/65.278ce63e.js"><link rel="prefetch" href="/assets/js/67.8c2201b6.js"><link rel="prefetch" href="/assets/js/68.46467c87.js"><link rel="prefetch" href="/assets/js/69.ee34297d.js"><link rel="prefetch" href="/assets/js/7.aaee1baa.js"><link rel="prefetch" href="/assets/js/70.3a016bcf.js"><link rel="prefetch" href="/assets/js/71.1cb787d0.js"><link rel="prefetch" href="/assets/js/72.2ee0677e.js"><link rel="prefetch" href="/assets/js/73.3e1e1729.js"><link rel="prefetch" href="/assets/js/74.947d7cd3.js"><link rel="prefetch" href="/assets/js/75.2e5c7344.js"><link rel="prefetch" href="/assets/js/76.6c098cc2.js"><link rel="prefetch" href="/assets/js/77.03fd3a89.js"><link rel="prefetch" href="/assets/js/78.38d2d963.js"><link rel="prefetch" href="/assets/js/79.ea508df9.js"><link rel="prefetch" href="/assets/js/8.35d0b089.js"><link rel="prefetch" href="/assets/js/80.b2b1dda3.js"><link rel="prefetch" href="/assets/js/81.d7db5a4d.js"><link rel="prefetch" href="/assets/js/82.1c148069.js"><link rel="prefetch" href="/assets/js/83.51e2c0d0.js"><link rel="prefetch" href="/assets/js/84.6118b266.js"><link rel="prefetch" href="/assets/js/85.55a516f8.js"><link rel="prefetch" href="/assets/js/86.3b73f7a9.js"><link rel="prefetch" href="/assets/js/87.123149cb.js"><link rel="prefetch" href="/assets/js/88.f87dde9d.js"><link rel="prefetch" href="/assets/js/89.06c3b9a1.js"><link rel="prefetch" href="/assets/js/9.58e6c220.js"><link rel="prefetch" href="/assets/js/vendors~flowchart.080f3458.js">
    <link rel="stylesheet" href="/assets/css/0.styles.324c77a5.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div><div class="theme-container" data-v-0b87bb44><div data-v-0b87bb44><div id="loader-wrapper" class="loading-wrapper" data-v-1c4f0192 data-v-0b87bb44 data-v-0b87bb44><div class="loader-main" data-v-1c4f0192><div data-v-1c4f0192></div><div data-v-1c4f0192></div><div data-v-1c4f0192></div><div data-v-1c4f0192></div></div> <!----> <!----></div> <div class="password-shadow password-wrapper-out" style="display:none;" data-v-73c95a87 data-v-0b87bb44 data-v-0b87bb44><h3 class="title" style="display:none;" data-v-73c95a87 data-v-73c95a87>flybird's blog</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-73c95a87 data-v-73c95a87><input type="password" value="" data-v-73c95a87> <span data-v-73c95a87>Konck! Knock!</span> <button data-v-73c95a87>OK</button></label> <div class="footer" style="display:none;" data-v-73c95a87 data-v-73c95a87><span data-v-73c95a87><i class="iconfont reco-theme" data-v-73c95a87></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-73c95a87>vuePress-theme-reco</a></span> <span data-v-73c95a87><i class="iconfont reco-copyright" data-v-73c95a87></i> <a data-v-73c95a87><span data-v-73c95a87>flybird</span>
            
          <span data-v-73c95a87>2020 - </span>
          2021
        </a></span></div></div> <div class="hide" data-v-0b87bb44><header class="navbar" data-v-0b87bb44><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><!----> <span class="site-name">flybird's blog</span></a> <div class="links"><div class="color-picker"><a class="color-button"><i class="iconfont reco-color"></i></a> <div class="color-picker-menu" style="display:none;"><div class="mode-options"><h4 class="title">Choose mode</h4> <ul class="color-mode-options"><li class="dark">dark</li><li class="auto active">auto</li><li class="light">light</li></ul></div></div></div> <div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/index.html" class="nav-link"><i class="iconfont reco-home"></i>
  主页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      分类
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/大数据/" class="nav-link"><i class="iconfont undefined"></i>
  大数据
</a></li><li class="dropdown-item"><!----> <a href="/categories/后端/" class="nav-link"><i class="iconfont undefined"></i>
  后端
</a></li><li class="dropdown-item"><!----> <a href="/categories/中间件/" class="nav-link"><i class="iconfont undefined"></i>
  中间件
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  标签
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间线
</a></div><div class="nav-item"><a href="/about/" class="nav-link"><i class="iconfont reco-message"></i>
  关于我
</a></div> <a href="https://github.com/f1ybird" target="_blank" rel="noopener noreferrer" class="repo-link"><i class="iconfont reco-github"></i>
    GitHub
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask" data-v-0b87bb44></div> <aside class="sidebar" data-v-0b87bb44><div class="personal-info-wrapper" data-v-7e653f02><img src="/vuepress/my-head.png" alt="author-avatar" class="personal-img" data-v-7e653f02> <h3 class="name" data-v-7e653f02>
    flybird
  </h3> <div class="num" data-v-7e653f02><div data-v-7e653f02><h3 data-v-7e653f02>63</h3> <h6 data-v-7e653f02>文章</h6></div> <div data-v-7e653f02><h3 data-v-7e653f02>26</h3> <h6 data-v-7e653f02>标签</h6></div></div> <hr data-v-7e653f02></div> <nav class="nav-links"><div class="nav-item"><a href="/index.html" class="nav-link"><i class="iconfont reco-home"></i>
  主页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      分类
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/大数据/" class="nav-link"><i class="iconfont undefined"></i>
  大数据
</a></li><li class="dropdown-item"><!----> <a href="/categories/后端/" class="nav-link"><i class="iconfont undefined"></i>
  后端
</a></li><li class="dropdown-item"><!----> <a href="/categories/中间件/" class="nav-link"><i class="iconfont undefined"></i>
  中间件
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  标签
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间线
</a></div><div class="nav-item"><a href="/about/" class="nav-link"><i class="iconfont reco-message"></i>
  关于我
</a></div> <a href="https://github.com/f1ybird" target="_blank" rel="noopener noreferrer" class="repo-link"><i class="iconfont reco-github"></i>
    GitHub
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav>  <ul class="sidebar-links"><li><a href="/views/" aria-current="page" class="sidebar-link">概览</a></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>大数据</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>中间件</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading open"><span>后端</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/views/java/ArrayList.html" class="sidebar-link">ArrayList底层实现和原理</a></li><li><a href="/views/java/HashMap.html" class="sidebar-link">HashMap底层实现和原理</a></li><li><a href="/views/java/docker.html" class="sidebar-link">Docker的基本了解和使用</a></li><li><a href="/views/java/itext.html" class="sidebar-link">itext:PDF导出</a></li><li><a href="/views/java/poi.html" class="sidebar-link">poi多线程多sheet导出Excel,csv</a></li><li><a href="/views/java/quartz.html" class="sidebar-link">Quartz定时任务</a></li><li><a href="/views/java/rabbitmq001.html" class="sidebar-link">RabbitMQ基础</a></li><li><a href="/views/java/rabbitmq002.html" class="sidebar-link">RabbitMQ进阶</a></li><li><a href="/views/java/redis01.html" class="sidebar-link">Redis基础</a></li><li><a href="/views/java/redis02.html" class="sidebar-link">Redis终结</a></li><li><a href="/views/java/SSH.html" class="sidebar-link">SSH架构知识点概览</a></li><li><a href="/views/java/jwt.html" class="sidebar-link">JWT登陆认证</a></li><li><a href="/views/java/swagger2.html" class="sidebar-link">Swagger2的基本了解和使用</a></li><li><a href="/views/java/thread.html" class="sidebar-link">多线程和线程池基础</a></li><li><a href="/views/java/ThreadPool.html" class="sidebar-link">线程池进阶详解</a></li><li><a href="/views/java/ThreadLocal.html" class="sidebar-link">ThreadLocal简介</a></li><li><a href="/views/java/annotationLog.html" class="sidebar-link">注解+AOP实现日志记录</a></li><li><a href="/views/java/jvm.html" class="sidebar-link">jvm和GC</a></li><li><a href="/views/java/JUC.html" class="sidebar-link">JUC小结</a></li><li><a href="/views/java/javaLock.html" class="sidebar-link">Java中的各种锁</a></li><li><a href="/views/java/mysql_explain.html" class="sidebar-link">MySQL慢查询优化</a></li><li><a href="/views/java/ReentrantLock.html" aria-current="page" class="active sidebar-link">ReentrantLock 详解</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/views/java/ReentrantLock.html#主要特性" class="sidebar-link">主要特性：</a></li><li class="sidebar-sub-header"><a href="/views/java/ReentrantLock.html#lock" class="sidebar-link">Lock</a></li><li class="sidebar-sub-header"><a href="/views/java/ReentrantLock.html#lock-过程" class="sidebar-link">lock() 过程</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/views/java/ReentrantLock.html#公平锁" class="sidebar-link">公平锁</a></li><li class="sidebar-sub-header"><a href="/views/java/ReentrantLock.html#非公平锁" class="sidebar-link">非公平锁</a></li></ul></li><li class="sidebar-sub-header"><a href="/views/java/ReentrantLock.html#unlock-过程" class="sidebar-link">unlock() 过程</a></li><li class="sidebar-sub-header"><a href="/views/java/ReentrantLock.html#lockinterruptibly-中断锁过程" class="sidebar-link">lockInterruptibly() 中断锁过程</a></li><li class="sidebar-sub-header"><a href="/views/java/ReentrantLock.html#trylock" class="sidebar-link">tryLock()</a></li><li class="sidebar-sub-header"><a href="/views/java/ReentrantLock.html#trylock-long-timeout-timeunit-unit" class="sidebar-link">tryLock(long timeout, TimeUnit unit)</a></li><li class="sidebar-sub-header"><a href="/views/java/ReentrantLock.html#reentrantlock-的等待-通知机制" class="sidebar-link">ReentrantLock 的等待 / 通知机制</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/views/java/ReentrantLock.html#newcondition" class="sidebar-link">newCondition()</a></li></ul></li><li class="sidebar-sub-header"><a href="/views/java/ReentrantLock.html#reentrantlock-和-synchronized-对比" class="sidebar-link">ReentrantLock 和 Synchronized 对比</a></li></ul></li></ul></section></li></ul> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-73c95a87 data-v-0b87bb44><h3 class="title" style="display:none;" data-v-73c95a87 data-v-73c95a87>ReentrantLock 详解</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-73c95a87 data-v-73c95a87><input type="password" value="" data-v-73c95a87> <span data-v-73c95a87>Konck! Knock!</span> <button data-v-73c95a87>OK</button></label> <div class="footer" style="display:none;" data-v-73c95a87 data-v-73c95a87><span data-v-73c95a87><i class="iconfont reco-theme" data-v-73c95a87></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-73c95a87>vuePress-theme-reco</a></span> <span data-v-73c95a87><i class="iconfont reco-copyright" data-v-73c95a87></i> <a data-v-73c95a87><span data-v-73c95a87>flybird</span>
            
          <span data-v-73c95a87>2020 - </span>
          2021
        </a></span></div></div> <div data-v-0b87bb44><main class="page"><!----> <div class="page-title" style="display:none;"><h1>ReentrantLock 详解</h1> <hr> <div data-v-7b2e794a><i class="iconfont reco-account" data-v-7b2e794a><span data-v-7b2e794a>flybird</span></i> <i class="iconfont reco-date" data-v-7b2e794a><span data-v-7b2e794a>2020-06-19</span></i> <i class="iconfont reco-eye" data-v-7b2e794a><span id="/views/java/ReentrantLock.html" data-flag-title="Your Article Title" class="leancloud-visitors" data-v-7b2e794a><a class="leancloud-visitors-count" style="font-size:.9rem;font-weight:normal;color:#999;"></a></span></i> <i class="iconfont reco-tag tags" data-v-7b2e794a><span class="tag-item" data-v-7b2e794a>
      源码分析
    </span><span class="tag-item" data-v-7b2e794a>
      多线程
    </span><span class="tag-item" data-v-7b2e794a>
      Java
    </span></i></div></div> <div class="theme-reco-content content__default" style="display:none;"><div id="boxx" data-v-f4ca0dac><div data-v-f4ca0dac><p v-if="true" class="custom-block-title" data-v-f4ca0dac></p> <p v-if="true" data-v-f4ca0dac></p></div></div> <p>可独占，可重入，可中断，可公平可非公平。</p> <p>引自掘金<a href="https://juejin.im/post/5ae1b4f0f265da0b7b359d7a#heading-2" target="_blank" rel="noopener noreferrer">hahaeee<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>和<a href="https://juejin.im/post/5c95df97e51d4551d06d8e8e" target="_blank" rel="noopener noreferrer">薛8<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>糅合而来。</p> <p></p><div class="table-of-contents"><ul><li><a href="#主要特性">主要特性：</a></li><li><a href="#lock">Lock</a></li><li><a href="#lock-过程">lock() 过程</a><ul><li><a href="#公平锁">公平锁</a></li><li><a href="#非公平锁">非公平锁</a></li></ul></li><li><a href="#unlock-过程">unlock() 过程</a></li><li><a href="#lockinterruptibly-中断锁过程">lockInterruptibly() 中断锁过程</a></li><li><a href="#trylock">tryLock()</a></li><li><a href="#trylock-long-timeout-timeunit-unit">tryLock(long timeout, TimeUnit unit)</a></li><li><a href="#reentrantlock-的等待-通知机制">ReentrantLock 的等待 / 通知机制</a><ul><li><a href="#newcondition">newCondition()</a></li></ul></li><li><a href="#reentrantlock-和-synchronized-对比">ReentrantLock 和 Synchronized 对比</a></li></ul></div><p></p> <h2 id="主要特性"><a href="#主要特性" class="header-anchor">#</a> 主要特性：</h2> <ol><li><p><strong>可重入</strong>。ReentrantLock 是可重入锁，因为它会记录之前获得锁线程对象，保存在 exclusiveOwenerThread 变量中，当一个线程要获取锁时，会先判断当前线程是不是已经获取锁的线程。synchronized 也是可重入锁。</p></li> <li><p><strong>可中断</strong>。ReentrantLock 是可中断锁，它提供了 lockInterruptibly 这种可中断的加锁方式，可以有效的避免线程之间因为互相持续占有资源而导致阻塞。synchronized 无法实现可中断。</p></li> <li><p><strong>公平锁与非公平锁可选</strong>。ReentrantLock 默认是非公平锁，但是也可以通过构造方法选择非公平锁。公平锁是指当多个线程尝试获取同一个锁时，获取锁的顺序按照到达的时间顺序排序。</p></li></ol> <p><img src="/znote/img/backEnd/16301aac714a64ae.jpg" alt="RenntrantLock"></p> <p><img src="/znote/img/backEnd/16301aac716e8f24.jpg" alt="依赖关系"></p> <p><code>斜体为抽象类,下横线为接口</code></p> <p><strong>聚合关系总结</strong>:</p> <ol><li>ReentrantLock 实现了 Lock,Serializable 接口</li> <li>ReentrantLock.Sync (内部类) 继承了 AQS</li> <li>ReentrantLock.NonfairSync 和 ReentrantLock.FairSync 继承了 ReentrantLock.Sync</li> <li>ReentrantLock 持有 ReentrantLock.Sync 对象 (实现锁功能)</li></ol> <p><strong>锁实现总结</strong>:</p> <ol><li>由 Node 节点组成一条同步队列 (有 head,tail 两个指针，并且 <strong>head 初始化时指向空节点</strong>)</li> <li>int state 标记锁使用数量 (独占锁时，通常为 1, 发生重入时&gt; 1)</li> <li>lock () 时加到队列尾部</li> <li>unlock () 时，释放 head 节点，并指向下一个节点 head=head.next, 然后唤醒当前 head 节点</li></ol> <p><strong>性质</strong>:</p> <ol><li>独占锁 (排它锁): 只能有一个线程获取锁</li> <li>重入锁：一个线程可以多次 lock ()</li> <li>公平 / 非公平锁：只针对上锁过程
<ol><li>非公平锁：尝试获取锁，若成功立刻返回，失败则加入同步队列</li> <li>公平锁：直接加入同步队列</li></ol></li></ol> <h2 id="lock"><a href="#lock" class="header-anchor">#</a> Lock</h2> <p>Lock 接口定义了锁的行为</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">Lock</span> <span class="token punctuation">{</span>
	<span class="token comment">//上锁(不响应Thread.interrupt()直到获取锁)</span>
    <span class="token keyword">void</span> <span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token comment">//上锁(响应Thread.interrupt())</span>
    <span class="token keyword">void</span> <span class="token function">lockInterruptibly</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">;</span>
	<span class="token comment">//尝试获取锁(以nonFair方式获取锁)</span>
    <span class="token keyword">boolean</span> <span class="token function">tryLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  	<span class="token comment">//在指定时间内尝试获取锁(响应Thread.interrupt(),支持公平/二阶段非公平)</span>
    <span class="token keyword">boolean</span> <span class="token function">tryLock</span><span class="token punctuation">(</span><span class="token keyword">long</span> time<span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span> unit<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">;</span>
	<span class="token comment">//解锁</span>
    <span class="token keyword">void</span> <span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token comment">//获取Condition</span>
    <span class="token class-name">Condition</span> <span class="token function">newCondition</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br></div></div><h2 id="lock-过程"><a href="#lock-过程" class="header-anchor">#</a> lock() 过程</h2> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">//锁具体实现</span>
<span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">Sync</span> sync<span class="token punctuation">;</span>
<span class="token comment">//根据传入参数选择FairSync或NonfairSync实现</span>
<span class="token keyword">public</span> <span class="token class-name">ReentrantLock</span><span class="token punctuation">(</span><span class="token keyword">boolean</span> fair<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        sync <span class="token operator">=</span> fair <span class="token operator">?</span> <span class="token keyword">new</span> <span class="token class-name">FairSync</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token keyword">new</span> <span class="token class-name">NonfairSync</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	sync<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock<span class="token punctuation">.</span>Sync</span>
<span class="token keyword">abstract</span> <span class="token keyword">void</span> <span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><h3 id="公平锁"><a href="#公平锁" class="header-anchor">#</a> 公平锁</h3> <p>加入同步队列 (当同步队列为空时会直接获得锁), 等待锁</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock<span class="token punctuation">.</span>FairSync</span>
<span class="token keyword">final</span> <span class="token keyword">void</span> <span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token function">acquire</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>
<span class="token keyword">public</span> <span class="token keyword">final</span> <span class="token keyword">void</span> <span class="token function">acquire</span><span class="token punctuation">(</span><span class="token keyword">int</span> arg<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">tryAcquire</span><span class="token punctuation">(</span>arg<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span><span class="token function">acquireQueued</span><span class="token punctuation">(</span><span class="token function">addWaiter</span><span class="token punctuation">(</span><span class="token class-name">Node</span><span class="token punctuation">.</span>EXCLUSIVE<span class="token punctuation">)</span><span class="token punctuation">,</span> arg<span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token function">selfInterrupt</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><p><strong>acquire () 流程</strong>:</p> <ol><li><p>tryAcquire (): 模板方法，获取锁</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code> #<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock<span class="token punctuation">.</span>FairSync</span>
 <span class="token keyword">protected</span> <span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">tryAcquire</span><span class="token punctuation">(</span><span class="token keyword">int</span> acquires<span class="token punctuation">)</span> <span class="token punctuation">{</span>
 	<span class="token comment">//获取当前线程</span>
    <span class="token keyword">final</span> <span class="token class-name">Thread</span> current <span class="token operator">=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> c <span class="token operator">=</span> <span class="token function">getState</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>c <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token comment">//当前锁没被占用</span>
 	   <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">hasQueuedPredecessors</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span><span class="token comment">//1.判断同步队列中是否有节点在等待</span>
 		   <span class="token function">compareAndSetState</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> acquires<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token comment">//2.如果上面!1成立,修改state值(表明当前锁已被占用)</span>
 		   <span class="token function">setExclusiveOwnerThread</span><span class="token punctuation">(</span>current<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//3.如果2成立,修改当前占用锁的线程为当前线程</span>
 		   <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
 	   <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>current <span class="token operator">==</span> <span class="token function">getExclusiveOwnerThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token comment">//占用锁线程==当前线程(重入)</span>
 	   <span class="token keyword">int</span> nextc <span class="token operator">=</span> c <span class="token operator">+</span> acquires<span class="token punctuation">;</span><span class="token comment">//</span>
 	   <span class="token keyword">if</span> <span class="token punctuation">(</span>nextc <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span>
 		   <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">Error</span><span class="token punctuation">(</span><span class="token string">&quot;Maximum lock count exceeded&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 	   <span class="token function">setState</span><span class="token punctuation">(</span>nextc<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//修改status</span>
 	   <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span><span class="token comment">//直接获取锁失败</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br></div></div></li> <li><p>acquireQueued (addWaiter (Node.EXCLUSIVE), arg): 加入同步队列</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>
<span class="token comment">//1</span>
<span class="token keyword">private</span> <span class="token class-name">Node</span> <span class="token function">addWaiter</span><span class="token punctuation">(</span><span class="token class-name">Node</span> mode<span class="token punctuation">)</span> <span class="token punctuation">{</span>
 <span class="token comment">//生成node</span>
    <span class="token class-name">Node</span> node <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Node</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> mode<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">Node</span> pred <span class="token operator">=</span> tail<span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>pred <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
 	<span class="token comment">//将node加到队列尾部</span>
 	   node<span class="token punctuation">.</span>prev <span class="token operator">=</span> pred<span class="token punctuation">;</span>
 	   <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">compareAndSetTail</span><span class="token punctuation">(</span>pred<span class="token punctuation">,</span> node<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
 		   pred<span class="token punctuation">.</span>next <span class="token operator">=</span> node<span class="token punctuation">;</span>
 		   <span class="token keyword">return</span> node<span class="token punctuation">;</span>
 	   <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    <span class="token comment">//如果加入失败(多线程竞争或者tail指针为null)</span>
    <span class="token function">enq</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> node<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token comment">//1.1  </span>
<span class="token keyword">private</span> <span class="token class-name">Node</span> <span class="token function">enq</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token class-name">Node</span> node<span class="token punctuation">)</span> <span class="token punctuation">{</span>
 <span class="token comment">//死循环加入节点(cas会失败)</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
 	   <span class="token class-name">Node</span> t <span class="token operator">=</span> tail<span class="token punctuation">;</span>
 	   <span class="token keyword">if</span> <span class="token punctuation">(</span>t <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment">//tail为null,同步队列初始化</span>
 		<span class="token comment">//设置head指针</span>
 		   <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">compareAndSetHead</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Node</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token comment">//注意这里是个空节点!!</span>
 			   tail <span class="token operator">=</span> head<span class="token punctuation">;</span><span class="token comment">//将tail也指向head</span>
 	   <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
 		   node<span class="token punctuation">.</span>prev <span class="token operator">=</span> t<span class="token punctuation">;</span><span class="token comment">//将当前node加到队尾</span>
 		   <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">compareAndSetTail</span><span class="token punctuation">(</span>t<span class="token punctuation">,</span> node<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
 			   t<span class="token punctuation">.</span>next <span class="token operator">=</span> node<span class="token punctuation">;</span>
 			   <span class="token keyword">return</span> t<span class="token punctuation">;</span><span class="token comment">//注意这里才返回</span>
 		   <span class="token punctuation">}</span>
 	   <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token comment">//2</span>
<span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">acquireQueued</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token class-name">Node</span> node<span class="token punctuation">,</span> <span class="token keyword">int</span> arg<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">boolean</span> failed <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token keyword">try</span> <span class="token punctuation">{</span>
 	<span class="token comment">//表示是否被打断</span>
 	   <span class="token keyword">boolean</span> interrupted <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
 	   <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
 		<span class="token comment">//获取node.pre节点</span>
 		   <span class="token keyword">final</span> <span class="token class-name">Node</span> p <span class="token operator">=</span> node<span class="token punctuation">.</span><span class="token function">predecessor</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 		   <span class="token keyword">if</span> <span class="token punctuation">(</span>p <span class="token operator">==</span> head <span class="token comment">//当前节点是否是同步队列中的第二个节点</span>
 		   <span class="token operator">&amp;&amp;</span> <span class="token function">tryAcquire</span><span class="token punctuation">(</span>arg<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token comment">//获取锁,head指向当前节点</span>
 			   <span class="token function">setHead</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//head=head.next</span>
 			   p<span class="token punctuation">.</span>next <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span><span class="token comment">//置空 </span>
 			   failed <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
 			   <span class="token keyword">return</span> interrupted<span class="token punctuation">;</span>
 		   <span class="token punctuation">}</span>

 		   <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">shouldParkAfterFailedAcquire</span><span class="token punctuation">(</span>p<span class="token punctuation">,</span> node<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token comment">//是否空转(因为空转唤醒是个耗时操作,进入空转前判断pre节点状态.如果pre节点即将释放锁,则不进入空转)</span>
 			   <span class="token function">parkAndCheckInterrupt</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token comment">//利用unsafe.park()进行空转(阻塞)</span>
 			   interrupted <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span><span class="token comment">//如果Thread.interrupt()被调用,(不会真的被打断,会继续循环空转直到获取到锁)</span>
 	   <span class="token punctuation">}</span>
    <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
 	   <span class="token keyword">if</span> <span class="token punctuation">(</span>failed<span class="token punctuation">)</span><span class="token comment">//tryAcquire()过程出现异常导致获取锁失败,则移除当前节点</span>
 		   <span class="token function">cancelAcquire</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br><span class="line-number">41</span><br><span class="line-number">42</span><br><span class="line-number">43</span><br><span class="line-number">44</span><br><span class="line-number">45</span><br><span class="line-number">46</span><br><span class="line-number">47</span><br><span class="line-number">48</span><br><span class="line-number">49</span><br><span class="line-number">50</span><br><span class="line-number">51</span><br><span class="line-number">52</span><br><span class="line-number">53</span><br><span class="line-number">54</span><br><span class="line-number">55</span><br><span class="line-number">56</span><br><span class="line-number">57</span><br><span class="line-number">58</span><br><span class="line-number">59</span><br><span class="line-number">60</span><br><span class="line-number">61</span><br><span class="line-number">62</span><br></div></div><p>过程总结:</p> <ol><li>空转 (如果当前节点是同步队列中的第二个节点，则直接获得锁返回)</li> <li>获得锁</li></ol> <blockquote><p>注意，这里有两次tryAcquire()过程：<br>
第一次，为了避免同步队列为空时还插入队列产生的性能耗费(cas空转)。<br>
第二次，就是正常的流程，先插入队尾，然后等待唤醒，再获取锁。</p></blockquote></li> <li><p>selfInterrupt (): 唤醒当前线程</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">selfInterrupt</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token comment">//在获取锁之后 响应intterpt()请求</span>
	<span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">interrupt</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div></li></ol> <h3 id="非公平锁"><a href="#非公平锁" class="header-anchor">#</a> 非公平锁</h3> <p>一阶段</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock<span class="token punctuation">.</span>NonfairSync</span>
<span class="token keyword">final</span> <span class="token keyword">void</span> <span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token comment">//在acquire()之前先尝试获取锁</span>
	<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">compareAndSetState</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token function">setExclusiveOwnerThread</span><span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">else</span>
		<span class="token function">acquire</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p>二阶段 acquire () 流程与公平锁一模一样，唯一区别在于 tryAcquire () 实现中</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock<span class="token punctuation">.</span>NonfairSync</span>
<span class="token keyword">protected</span> <span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">tryAcquire</span><span class="token punctuation">(</span><span class="token keyword">int</span> acquires<span class="token punctuation">)</span> <span class="token punctuation">{</span>
 	<span class="token keyword">return</span> <span class="token function">nonfairTryAcquire</span><span class="token punctuation">(</span>acquires<span class="token punctuation">)</span><span class="token punctuation">;</span>
 <span class="token punctuation">}</span>
 
#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock<span class="token punctuation">.</span>Sync</span>
 <span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">nonfairTryAcquire</span><span class="token punctuation">(</span><span class="token keyword">int</span> acquires<span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token comment">//这个过程其实和FairSync.tryAcquire()基本一致</span>
	<span class="token keyword">final</span> <span class="token class-name">Thread</span> current <span class="token operator">=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">int</span> c <span class="token operator">=</span> <span class="token function">getState</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">if</span> <span class="token punctuation">(</span>c <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token comment">//唯一区别: 这里不会去判断队列中是否为空</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">compareAndSetState</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> acquires<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			<span class="token function">setExclusiveOwnerThread</span><span class="token punctuation">(</span>current<span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>current <span class="token operator">==</span> <span class="token function">getExclusiveOwnerThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token keyword">int</span> nextc <span class="token operator">=</span> c <span class="token operator">+</span> acquires<span class="token punctuation">;</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span>nextc <span class="token operator">&lt;</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token comment">// overflow</span>
			<span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">Error</span><span class="token punctuation">(</span><span class="token string">&quot;Maximum lock count exceeded&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token function">setState</span><span class="token punctuation">(</span>nextc<span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br></div></div><table><thead><tr><th>区别点</th> <th>lock () 过程 (一阶段)</th> <th>tryAcquire () 过程 (二阶段)</th></tr></thead> <tbody><tr><td>FairSync</td> <td>直接 acquire ()</td> <td>当前若无线程持有锁，如果同步队列为空，获取锁</td></tr> <tr><td>NonFairSync</td> <td>先尝试获取锁，再 acquire ()</td> <td>当前若无线程持有锁，获取锁</td></tr></tbody></table> <h2 id="unlock-过程"><a href="#unlock-过程" class="header-anchor">#</a> unlock() 过程</h2> <div class="language-java line-numbers-mode"><pre class="language-java"><code>#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	sync<span class="token punctuation">.</span><span class="token function">release</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>
<span class="token keyword">public</span> <span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">release</span><span class="token punctuation">(</span><span class="token keyword">int</span> arg<span class="token punctuation">)</span> <span class="token punctuation">{</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">tryRelease</span><span class="token punctuation">(</span>arg<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token comment">//释放锁</span>
	<span class="token class-name">Node</span> h <span class="token operator">=</span> head<span class="token punctuation">;</span>
	<span class="token keyword">if</span> <span class="token punctuation">(</span>h <span class="token operator">!=</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span><span class="token comment">//head节点为空(非公平锁直接获取锁)</span>
	h<span class="token punctuation">.</span>waitStatus <span class="token operator">!=</span> <span class="token number">0</span><span class="token punctuation">)</span>
		<span class="token function">unparkSuccessor</span><span class="token punctuation">(</span>h<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//唤醒同步队列中离head最近的一个waitStatus&lt;=0的节点</span>
	<span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>
<span class="token keyword">protected</span> <span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">tryRelease</span><span class="token punctuation">(</span><span class="token keyword">int</span> releases<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">int</span> c <span class="token operator">=</span> <span class="token function">getState</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span> releases<span class="token punctuation">;</span>
	<span class="token comment">//持有锁的线程==当前线程</span>
	<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token function">getExclusiveOwnerThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalMonitorStateException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">boolean</span> free <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
	<span class="token keyword">if</span> <span class="token punctuation">(</span>c <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token comment">//重入锁全部释放</span>
		free <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
		<span class="token comment">//置空持有锁线程</span>
		<span class="token function">setExclusiveOwnerThread</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">}</span>
	<span class="token comment">//state==0(此时持有锁,不用cas)</span>
	<span class="token function">setState</span><span class="token punctuation">(</span>c<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">return</span> free<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br></div></div><h2 id="lockinterruptibly-中断锁过程"><a href="#lockinterruptibly-中断锁过程" class="header-anchor">#</a> lockInterruptibly() 中断锁过程</h2> <p>lockInterruptibly () 与 lock () 过程基本相同，区别在于 Thread.intterpt () 的应对措施不同。</p> <p>ReentrantLock 中的 lockInterruptibly () 方法使得线程可以在被阻塞时响应中断，<code>比如一个线程 t1 通过 lockInterruptibly() 方法获取到一个可重入锁，并执行一个长时间的任务，另一个线程通过 lockInterruptibly() 方法就可以立刻打断 t1 线程的执行，来获取 t1 持有的那个可重入锁。</code>而通过 ReentrantLock 的 lock () 方法或者 Synchronized 持有锁的线程是不会响应其他线程的 interrupt () 方法的，直到该方法主动释放锁之后才会响应 interrupt () 方法。</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">//lock()</span>
<span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">acquireQueued</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token class-name">Node</span> node<span class="token punctuation">,</span> <span class="token keyword">int</span> arg<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">boolean</span> failed <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
	<span class="token keyword">try</span> <span class="token punctuation">{</span>
		<span class="token comment">//表示是否被打断</span>
		<span class="token keyword">boolean</span> interrupted <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
		<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			<span class="token comment">//获取node.pre节点</span>
			<span class="token keyword">final</span> <span class="token class-name">Node</span> p <span class="token operator">=</span> node<span class="token punctuation">.</span><span class="token function">predecessor</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token keyword">if</span> <span class="token punctuation">(</span>p <span class="token operator">==</span> head <span class="token comment">//当前节点是否是同步队列中的第二个节点</span>
			<span class="token operator">&amp;&amp;</span> <span class="token function">tryAcquire</span><span class="token punctuation">(</span>arg<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token comment">//获取锁,当前head指向当前节点</span>
				<span class="token function">setHead</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//head=head.next</span>
				p<span class="token punctuation">.</span>next <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span><span class="token comment">//置空 </span>
				failed <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
				<span class="token keyword">return</span> interrupted<span class="token punctuation">;</span>
			<span class="token punctuation">}</span>

			<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">shouldParkAfterFailedAcquire</span><span class="token punctuation">(</span>p<span class="token punctuation">,</span> node<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> <span class="token comment">//是否空转(因为空转唤醒是个耗时操作,进入空转前判断pre节点状态.如果pre节点即将释放锁,则不进入空转)</span>
				<span class="token function">parkAndCheckInterrupt</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token comment">//利用unsafe.park()进行空转(阻塞)</span>
				interrupted <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span><span class="token comment">//如果Thread.interrupt()被调用,(不会真的被打断,会继续循环空转直到获取到锁)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span>failed<span class="token punctuation">)</span><span class="token comment">//tryAcquire()过程出现异常导致获取锁失败,则移除当前节点</span>
			<span class="token function">cancelAcquire</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token comment">// lockInterruptibly()</span>
<span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">doAcquireInterruptibly</span><span class="token punctuation">(</span><span class="token keyword">int</span> arg<span class="token punctuation">)</span>
	<span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">{</span>
	<span class="token keyword">final</span> <span class="token class-name">Node</span> node <span class="token operator">=</span> <span class="token function">addWaiter</span><span class="token punctuation">(</span><span class="token class-name">Node</span><span class="token punctuation">.</span>EXCLUSIVE<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">boolean</span> failed <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
	<span class="token keyword">try</span> <span class="token punctuation">{</span>
		<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			<span class="token keyword">final</span> <span class="token class-name">Node</span> p <span class="token operator">=</span> node<span class="token punctuation">.</span><span class="token function">predecessor</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token keyword">if</span> <span class="token punctuation">(</span>p <span class="token operator">==</span> head <span class="token operator">&amp;&amp;</span> <span class="token function">tryAcquire</span><span class="token punctuation">(</span>arg<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
				<span class="token function">setHead</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span>
				p<span class="token punctuation">.</span>next <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span> 
				failed <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
				<span class="token keyword">return</span><span class="token punctuation">;</span>
			<span class="token punctuation">}</span>
			<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">shouldParkAfterFailedAcquire</span><span class="token punctuation">(</span>p<span class="token punctuation">,</span> node<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span>
				<span class="token function">parkAndCheckInterrupt</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token comment">//唯一区别当Thread.intterpt()打断时,直接抛出异常</span>
				<span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span>failed<span class="token punctuation">)</span><span class="token comment">//然后移除当前节点</span>
			<span class="token function">cancelAcquire</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br><span class="line-number">41</span><br><span class="line-number">42</span><br><span class="line-number">43</span><br><span class="line-number">44</span><br><span class="line-number">45</span><br><span class="line-number">46</span><br><span class="line-number">47</span><br><span class="line-number">48</span><br><span class="line-number">49</span><br></div></div><ul><li>中断锁代码测试：<a href="https://blog.csdn.net/dongyuxu342719/article/details/94395877" target="_blank" rel="noopener noreferrer">CSDN<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul> <h2 id="trylock"><a href="#trylock" class="header-anchor">#</a> tryLock()</h2> <div class="language-java line-numbers-mode"><pre class="language-java"><code>#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>
<span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">tryLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token comment">//尝试获取非公平锁</span>
	<span class="token keyword">return</span> sync<span class="token punctuation">.</span><span class="token function">nonfairTryAcquire</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><h2 id="trylock-long-timeout-timeunit-unit"><a href="#trylock-long-timeout-timeunit-unit" class="header-anchor">#</a> tryLock(long timeout, TimeUnit unit)</h2> <div class="language-java line-numbers-mode"><pre class="language-java"><code>#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock</span>
<span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">tryLock</span><span class="token punctuation">(</span><span class="token keyword">long</span> timeout<span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span> unit<span class="token punctuation">)</span>
		<span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">{</span>
	<span class="token keyword">return</span> sync<span class="token punctuation">.</span><span class="token function">tryAcquireNanos</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> unit<span class="token punctuation">.</span><span class="token function">toNanos</span><span class="token punctuation">(</span>timeout<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>AbstractQueuedSynchronizer</span>
<span class="token keyword">public</span> <span class="token keyword">final</span> <span class="token keyword">boolean</span> <span class="token function">tryAcquireNanos</span><span class="token punctuation">(</span><span class="token keyword">int</span> arg<span class="token punctuation">,</span> <span class="token keyword">long</span> nanosTimeout<span class="token punctuation">)</span>
		<span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">interrupted</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">return</span> <span class="token function">tryAcquire</span><span class="token punctuation">(</span>arg<span class="token punctuation">)</span> <span class="token operator">||</span><span class="token comment">//获取锁(公平/非公平)</span>
		<span class="token function">doAcquireNanos</span><span class="token punctuation">(</span>arg<span class="token punctuation">,</span> nanosTimeout<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//在指定时间内等待锁(空转)</span>
<span class="token punctuation">}</span>

<span class="token keyword">private</span> <span class="token keyword">boolean</span> <span class="token function">doAcquireNanos</span><span class="token punctuation">(</span><span class="token keyword">int</span> arg<span class="token punctuation">,</span> <span class="token keyword">long</span> nanosTimeout<span class="token punctuation">)</span>
		<span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span> <span class="token punctuation">{</span>
	<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
	<span class="token keyword">final</span> <span class="token keyword">long</span> deadline <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">nanoTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> nanosTimeout<span class="token punctuation">;</span>
	<span class="token comment">//加入队尾</span>
	<span class="token keyword">final</span> <span class="token class-name">Node</span> node <span class="token operator">=</span> <span class="token function">addWaiter</span><span class="token punctuation">(</span><span class="token class-name">Node</span><span class="token punctuation">.</span>EXCLUSIVE<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token keyword">boolean</span> failed <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
	<span class="token keyword">try</span> <span class="token punctuation">{</span>
		<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token punctuation">;</span><span class="token punctuation">;</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			<span class="token keyword">final</span> <span class="token class-name">Node</span> p <span class="token operator">=</span> node<span class="token punctuation">.</span><span class="token function">predecessor</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token keyword">if</span> <span class="token punctuation">(</span>p <span class="token operator">==</span> head <span class="token operator">&amp;&amp;</span> <span class="token function">tryAcquire</span><span class="token punctuation">(</span>arg<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
				<span class="token function">setHead</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span>
				p<span class="token punctuation">.</span>next <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span> 
				failed <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
				<span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
			<span class="token punctuation">}</span>
		  <span class="token comment">//上面与acquireQueued()相同,重点看这里</span>
		  <span class="token comment">//计算剩余时间</span>
			nanosTimeout <span class="token operator">=</span> deadline <span class="token operator">-</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">nanoTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token keyword">if</span> <span class="token punctuation">(</span>nanosTimeout <span class="token operator">&lt;=</span> <span class="token number">0L</span><span class="token punctuation">)</span>
				<span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
			<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">shouldParkAfterFailedAcquire</span><span class="token punctuation">(</span>p<span class="token punctuation">,</span> node<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span>
				nanosTimeout <span class="token operator">&gt;</span> spinForTimeoutThreshold<span class="token punctuation">)</span>
				<span class="token comment">//利用parkNanos()指定空转时间</span>
				<span class="token class-name">LockSupport</span><span class="token punctuation">.</span><span class="token function">parkNanos</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> nanosTimeout<span class="token punctuation">)</span><span class="token punctuation">;</span>
			<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">interrupted</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token comment">//如果被Thread.interrupt(),则抛异常</span>
				<span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
		<span class="token keyword">if</span> <span class="token punctuation">(</span>failed<span class="token punctuation">)</span><span class="token comment">//移除节点</span>
			<span class="token function">cancelAcquire</span><span class="token punctuation">(</span>node<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br><span class="line-number">41</span><br><span class="line-number">42</span><br><span class="line-number">43</span><br><span class="line-number">44</span><br><span class="line-number">45</span><br><span class="line-number">46</span><br><span class="line-number">47</span><br></div></div><h2 id="reentrantlock-的等待-通知机制"><a href="#reentrantlock-的等待-通知机制" class="header-anchor">#</a> ReentrantLock 的等待 / 通知机制</h2> <h3 id="newcondition"><a href="#newcondition" class="header-anchor">#</a> newCondition()</h3> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token class-name">Condition</span> <span class="token function">newCondition</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">return</span> sync<span class="token punctuation">.</span><span class="token function">newCondition</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
#<span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>locks<span class="token punctuation">.</span></span>ReentrantLock<span class="token punctuation">.</span>Sync</span>
<span class="token keyword">final</span> <span class="token class-name">ConditionObject</span> <span class="token function">newCondition</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">ConditionObject</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><ul><li>等待和唤醒</li></ul> <p>我们知道关键字 <code>Synchronized</code> + <code>Object</code> 的 <code>wait</code> 和 <code>notify</code>、<code>notifyAll</code> 方法能实现<strong>等待 / 通知</strong>机制，那么 <code>ReentrantLock</code> 是否也能实现这样的等待 / 通知机制，答案是：可以。
<code>ReentrantLock</code> 通过 <code>Condition</code> 对象，也就是<strong>条件队列</strong>实现了和 <code>wait</code>、<code>notify</code>、<code>notifyAll</code> 相同的语义。 线程执行 <code>condition.await()</code> 方法，将节点 1 从同步队列转移到条件队列中。</p> <p><img src="/znote/img/backEnd/169b3432b128105d.jpg" alt="img"></p> <p>线程执行 <code>condition.signal()</code> 方法，将节点 1 从条件队列中转移到同步队列。</p> <p><img src="/znote/img/backEnd/169b3411b74cfff1.jpg" alt="img"></p> <p>因为只有在同步队列中的线程才能去获取锁，所以通过 <code>Condition</code> 对象的 <code>wait</code> 和 <code>signal</code> 方法能实现等待 / 通知机制。</p> <ul><li>等待和唤醒部分</li></ul> <p>如果想单独唤醒部分线程应该怎么做呢？这时就有必要使用多个 <code>Condition</code> 对象了，因为 <code>ReentrantLock</code> 支持创建多个 <code>Condition</code> 对象，例如：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">//为了减少篇幅 仅给出伪代码</span>
<span class="token class-name">ReentrantLock</span> lock <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ReentrantLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">Condition</span> condition <span class="token operator">=</span> lock<span class="token punctuation">.</span><span class="token function">newCondition</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">Condition</span> condition1 <span class="token operator">=</span> lock<span class="token punctuation">.</span><span class="token function">newCondition</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">//线程1 调用condition.await() 线程进入到条件队列</span>
condition<span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">//线程2 调用condition1.await() 线程进入到条件队列</span>
condition1<span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">//线程32 调用condition.signal() 仅唤醒调用condition中的线程，不会影响到调用condition1。</span>
condition1<span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br></div></div><p>这样就实现了部分唤醒的功能。</p> <h2 id="reentrantlock-和-synchronized-对比"><a href="#reentrantlock-和-synchronized-对比" class="header-anchor">#</a> ReentrantLock 和 Synchronized 对比</h2> <table><thead><tr><th></th> <th>ReentrantLock</th> <th>Synchronized</th></tr></thead> <tbody><tr><td>底层实现</td> <td>通过 <code>AQS</code> 实现</td> <td>通过 <code>JVM</code> 实现，其中 <code>synchronized</code> 又有多个类型的锁，除了重量级锁是通过 <code>monitor</code> 对象 (操作系统 mutex 互斥原语) 实现外，其它类型的通过对象头实现。</td></tr> <tr><td>是否可重入</td> <td>是</td> <td>是</td></tr> <tr><td>公平锁</td> <td>是</td> <td>否</td></tr> <tr><td>非公平锁</td> <td>是</td> <td>是</td></tr> <tr><td>锁的类型</td> <td>悲观锁、显式锁</td> <td>悲观锁、隐式锁 (内置锁)</td></tr> <tr><td>是否支持中断</td> <td>是</td> <td>否</td></tr> <tr><td>是否支持超时等待</td> <td>是</td> <td>否</td></tr> <tr><td>是否自动获取 / 释放锁</td> <td>否</td> <td>是</td></tr></tbody></table></div> <footer class="page-edit" style="display:none;"><div class="edit-link"><a href="https://github.com/f1ybird/edit/master/docs/views/java/ReentrantLock.md" target="_blank" rel="noopener noreferrer">在 GitHub 上编辑此页！</a> <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></div> <div class="last-updated"><span class="prefix">Last Updated: </span> <span class="time">2020-06-21 23:07:31</span></div></footer> <!----> <!----></main> <!----> <div class="comments-wrapper" style="display:none;" data-v-0b87bb44><div class="valine-wrapper"><div id="valine"></div></div></div></div></div></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-44bd5a18 data-v-44bd5a18><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-44bd5a18><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-44bd5a18></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-44bd5a18></path></svg></div><!----><div data-v-48108b4c><div class="DetailsOpenFlag" style="right:1rem;bottom:9rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;font-size:14px;font-weight:500;display:none;" data-v-48108b4c>
 展开 

</div></div></div></div>
    <script src="/assets/js/app.55c4f7c3.js" defer></script><script src="/assets/js/5.86109dd2.js" defer></script><script src="/assets/js/1.74974061.js" defer></script><script src="/assets/js/2.ab8aa845.js" defer></script><script src="/assets/js/66.cb493053.js" defer></script><script src="/assets/js/18.cfe435f1.js" defer></script>
  </body>
</html>
